package bootstrap

import (
	_ "go-toy/command"
	_ "go-toy/database/orm"
	"go-toy/middleware/logger"
	"go-toy/middleware/recovery"
	"go-toy/router"
	"go-toy/util"

	"github.com/gin-gonic/gin"
)

var Engine *gin.Engine

type core struct {
}

// RegisterEngine register the gin engine
func (c *core) RegisterEngine() {

	// Set the gin mode from the config
	gin.SetMode(util.Viper.GetString("env"))

	// Use gin.Default() and it had inlcuded some middlewares which are logger and recovery
	// Initialize the router
	// Engine = gin.Default()

	// So,use gin.New() to create a new router without any middleware
	Engine = gin.New()

	// Next one,use gin.Engine.Use() to add middlewares which created by yourself

	// Use the logger middleware which yourself created
	Engine.Use(logger.FactoryInstance.Handle())

	// Use the recovery middleware which yourself created
	Engine.Use(recovery.SimpleIntance.Handle())

	// Set the router to trust the proxy
	Engine.SetTrustedProxies(util.Viper.GetStringSlice("http.trustedProxies"))

	router.Run(Engine)
}

func (c *core) Run() {
	c.RegisterEngine()

	if err := Engine.Run(util.Viper.GetString("addr")); err != nil {
		panic(err)
	}
}

var Core *core = &core{}
